package Singleton;

//饿汉模式
/*class Singleton{
    private  Singleton instance =  new Singleton();
    private Singleton(){}
    public Singleton getSingleton(){
        return instance;
    }
}*/

//懒汉模式（单线程版本）
/*class Singleton{
    private static Singleton instance = null;
    private Singleton(){}
    public Singleton getInstance(){
        if(instance == null)
        instance = new Singleton();
        return instance;
    }
}*/

//懒汉模式 （多线程版本）
/*class Singleton {
    private static Singleton instance = null;
    private Singleton(){}
    public  synchronized Singleton getSingleton(){
        if(instance == null)
        {
           instance = new Singleton();
        }
        return instance;
    }
}*/

//懒汉模式 （多线程改进版本，减少锁的竞争）
class SingletonLazy {
    private static volatile SingletonLazy instance = null;
    private static  Object locker  = new Object();

    public static SingletonLazy getInstance() {
        if (instance == null) {
            synchronized (locker) {
                if (instance == null) {
                    instance = new SingletonLazy();
                }
            }
        }
        return instance;
    }

   private SingletonLazy(){}
}
public class demo1 {
    public static void main(String[] args) {
        SingletonLazy s1 =  SingletonLazy.getInstance();
        SingletonLazy s2 =  SingletonLazy.getInstance();
        System.out.println(s1 == s2);

    }
}
